/**
 * FORM 表单演示 - 时间选择与默认值
 *
 */
import { Form, Button, DatePicker, TimePicker } from "antd";
import dayjs from "dayjs";

const App: React.FC = () => {
  //表单
  const [form] = Form.useForm();

  // 默认值
  const initialRange = [
    dayjs("2024-05-01 12:00:00"),
    dayjs("2024-05-10 12:00:00"),
  ];

  const initialValues = {
    date: [dayjs("2024-05-01"), dayjs("2024-05-02")],
    time: dayjs("12:00:00", "HH:mm:ss"),
    time_period: initialRange, //
  };

  //打印表单内容
  const show = () => {
    console.log(form.getFieldsValue());
    console.log(form.getFieldsValue().time.timeString);

    //复制一份
    const values = form.getFieldsValue();

    //拿到时间
    const { date, time, time_period } = values;

    //格式化并替换
    values.date = date.map((item: any) => item.format("YYYY-MM-DD"));

    //values.time = dayjs(time).format("HH:mm:ss");
    values.time = time.timeString;

    values.time_period = time_period.map((item: any) =>
      dayjs(item).format("YYYY-MM-DD HH:mm:ss")
    );

    //打印
    console.log(values);
  };

  //准备组件
  const { RangePicker } = DatePicker;

  // 处理表单提交
  const onFinish = (values: any) => {
    const { time } = values;
    // 格式化时间
    const formattedTime = dayjs(time).format("HH:mm:ss");

    // 打印格式化后的时间
    console.log("Formatted Time:", formattedTime);

    // 这里可以将 formattedTime 存储到状态或数据库中
  };

  return (
    <>
      <Form
        form={form}
        name="f"
        style={{ maxWidth: 600 }}
        initialValues={initialValues} // 设置表单的初始值
        onFinish={onFinish}
      >
        <Form.Item>
          <h1>时间</h1>
        </Form.Item>
        <Form.Item label="日期" name="date">
          <RangePicker />
        </Form.Item>
        <Form.Item label="时间" name="time">
          <TimePicker format="HH:mm:ss" />
        </Form.Item>

        <Form.Item label="时间段" name="time_period">
          <RangePicker
            showTime={{ format: "HH:mm" }}
            format="YYYY-MM-DD HH:mm"
            onChange={(value, dateString) => {
              console.log("时间对象: ", value);
              console.log("时间段: ", dateString);
            }}
          />
        </Form.Item>

        <Form.Item>
          <Button onClick={show}>打印表格</Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default App;
